"""
@Author : 合肥一元数智教育科技有限公司
@Date :  2025/6/6 10:58
@Description :   socket client

"""
import socket
import threading


class ChatClient:
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 连接服务器
    def connect_server(self):
        print('开始连接服务端....')
        try:
            self.socket.connect((self.ip, self.port))
            print('服务端连接成功....')
            return  True
        except ConnectionRefusedError:
            print('服务器连接失败....')
            return False

    # 发送数据
    def send_message(self):
        while True:
            message = input('>>')
            if message == 'exit':
                self.socket.close()
                break
            if message:
                self.socket.send(message.encode('utf-8'))
            else:
                print('消息不能为空')
                continue

    # 接收数据
    def receive_message(self):
        try:
            while True:
                data = self.socket.recv(1024).decode('utf-8')
                if data:
                    print(data)
                    print('>>', end='')
        except ConnectionAbortedError:  # 主动关闭 client
            print('客户端已离线...')
        except ConnectionResetError:
            print('服务器异常,请重新连接...')



if __name__ == '__main__':
    chat_client = ChatClient('192.168.1.226', 9999)
    is_connected = chat_client.connect_server()
    if is_connected:
        # 创建线程  接收消息
        thread_recv = threading.Thread(target=chat_client.receive_message)
        thread_recv.start()
        # 创建线程发送消息
        thread_send = threading.Thread(target=chat_client.send_message)
        thread_send.start()
